package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wmz
 * @date 2024/1/25 13:51
 * @description DishServiceImpl
 */
@Service("dishService")
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private FlavorMapper flavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        //获取菜品
        BeanUtils.copyProperties(dishDTO,dish);
        //调用mapper层方法（sql使用了主键回显）
        dishMapper.saveWithFlavor(dish);
        //获取菜品主键值
        Long dishId = dish.getId();
        //获取口味
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        if(flavorList != null && flavorList.size() > 0) {
            //向口味表设置dish_id
            flavorList.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            //批量插入
            flavorMapper.insertFlavor(flavorList);
        }
    }

    /**
     * 分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //开始分页查询
        //基于PageHelper插件实现动态分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 删除菜品
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        //查询ids菜品
        List<Dish> dishList = dishMapper.queryDishByIds(ids);
        //1.起售中的菜品不能删除
        dishList.forEach(dish -> {
            if(dish.getStatus() == StatusConstant.ENABLE){
                //当前菜品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //2.被套餐关联的菜品不能删除
        List<Long> setmealIds = setmealMapper.querySetmealIdsByDishIds(ids);
        if(setmealIds != null && setmealIds.size() > 0 ) {
            //选中的菜品被关联，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3.删除菜品表中的菜品数据
        dishMapper.deleteDishByIds(ids);
        //4.删除菜品关联的口味数据
        flavorMapper.deleteFlavorByDishIds(ids);
    }

    /**
     * 实现菜品起售/停售
     * @param status
     * @param id
     */
    @Override
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = new Dish().builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);
        if(status == StatusConstant.DISABLE){
            //如果是停售状态， 则包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = setmealMapper.querySetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }
    /**
     * 根据id查询菜品
     * @param id
     * @return
     */

    @Override
    public DishVO queryDishWithFlavorById(Long id) {
        DishVO dishVO = new DishVO();
        //查询菜品
        Dish dish = dishMapper.selectById(id);
        //查询口味
        List<DishFlavor> dishFlavorList = flavorMapper.selectFlavorByDishId(id);
        //封装数据
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //1.修改dish
        dishMapper.update(dish);

        //2.修改flavor
        Long dishId = dishDTO.getId();
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        //2.1删除dishId的所有口味信息
        flavorMapper.deleteFlavorByDishId(dishId);
        //2.2新增dishId的口味信息
        if (flavorList != null && flavorList.size() > 0) {
            //向口味表设置dish_id
            flavorList.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            //批量插入
            flavorMapper.insertFlavor(flavorList);
        }
    }

    /**
     * 根据categoryId展示
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = new Dish().builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.selectByCategoryId(dish);
    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.selectByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorMapper.selectFlavorByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
